//
//  BoozeTableViewController.m
//  VeganIsEasy
//
//  Created by Matthew Feinberg on 5/30/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "BoozeTableViewController.h"
#import "BoozeDetailsViewController.h"
#import "BoozeCompanyVC.h"

@implementation BoozeTableViewController

@synthesize boozes;
@synthesize searchBar;
@synthesize sectionTitles;
@synthesize rowsPerSection;
@synthesize startRowBySection;
@synthesize overlayController;

- (id)initWithDatabase:(sqlite3*)newDatabase {
	
	database = newDatabase;

	[self reloadBoozesWithQuery:nil];
	
	[self init];

	// Set up the tab bar button
	[self.tabBarItem initWithTitle:@"Booze"	image:[UIImage imageNamed:@"beer_tab.png"] tag:(NSInteger)NULL]; // createImage((float)10) tag:(NSInteger)NULL];
//	[[self tabBarItem] setTitle:@"Booze"];
	
	// Create and add the search bar
	UISearchBar *newSearchBar = [[UISearchBar alloc] init];
	newSearchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	[newSearchBar setPrompt:@"Search Booze"];
	self.navigationItem.titleView = newSearchBar;
	self.navigationItem.titleView.frame = CGRectMake(0, 0, 320,44);	
	[newSearchBar setDelegate:self];
	[self setSearchBar:newSearchBar];
	[newSearchBar release];

	searching = NO;
	
	return self;
}

- (void)reloadBoozesWithQuery:(NSString *)query {
	NSMutableArray *boozesArray = [[NSMutableArray alloc] init];
	[self setBoozes:boozesArray];
	[boozesArray release];
	
	char *sql;
	const char* likeQuery;
	if (query == nil) {
		sql = "SELECT id, company_name, status, booze_type FROM company ORDER BY company_name";	
	}
	else {
		sql = "SELECT id, company_name, status, booze_type FROM company WHERE company_name LIKE ? ORDER BY company_name";
		likeQuery = [[NSString stringWithFormat:@"%%%@%%", query] UTF8String];	
	}	
	
	sqlite3_stmt *statement = nil;
	if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
		if (query != nil) {
			sqlite3_bind_text(statement, 1, likeQuery, -1, NULL);
		}
		while (sqlite3_step(statement) == SQLITE_ROW) {
			NSMutableArray *row = [[NSMutableArray alloc] init];
			[row addObject:[NSNumber numberWithInteger:sqlite3_column_int(statement, 0)]];
			[row addObject: [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)]];
			[row addObject: [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)]];
			[row addObject: [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)]];
			[boozesArray addObject:row];
			[row release];
		}
	}
	sqlite3_finalize(statement);
	
	NSMutableArray *newSectionTitles = [[NSMutableArray alloc] init];
	NSMutableArray *newRowsPerSection = [[NSMutableArray alloc] init];
	NSMutableArray *newStartRowBySection = [[NSMutableArray alloc] init];
	
	[self setSectionTitles:newSectionTitles];
	[newSectionTitles release];
	
	[self setRowsPerSection:newRowsPerSection];
	[newRowsPerSection release];
	
	[self setStartRowBySection:newStartRowBySection];
	[newStartRowBySection release];
	
	if (query == nil) {
		sql = "select upper(substr(company_name, 1, 1)) AS section, count(*) FROM company GROUP BY upper(substr(company_name, 1, 1)) ORDER BY section";
	}
	else {
		sql = "select upper(substr(company_name, 1, 1)) AS section, count(*) FROM company WHERE company_name LIKE ? GROUP BY upper(substr(company_name, 1, 1)) ORDER BY section";
	}
	int iStartRow = 0;
	if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
		if (query != nil) {
			sqlite3_bind_text(statement, 1, likeQuery, -1, NULL);
		}
		while (sqlite3_step(statement) == SQLITE_ROW) {
			[sectionTitles addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]];
			int iRowCount = sqlite3_column_int(statement, 1);
			[rowsPerSection addObject:[NSNumber numberWithInteger:iRowCount]];
			[startRowBySection addObject:[NSNumber numberWithInteger:iStartRow]];
			iStartRow += iRowCount;
			//			[boozesArray release];
		}
	}
	sqlite3_finalize(statement);
}

//- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar;                      // return NO to not become first responder

// called when text starts editing
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {

	// Scroll to the top of the tableView
	[self.tableView setContentOffset:CGPointMake(0, 0) animated:NO];
	
	// Add the overlay view
	if (overlayController == nil) {
		CGFloat width = self.view.frame.size.width;
		CGFloat height = self.view.frame.size.height;
	
//		CGFloat y = self.tableView.contentOffset.y;
		
		// Create the frame where the overlay will go
		CGRect frame = CGRectMake(0, 0, width, height);
		OverlayViewController *newOverlayController = [[OverlayViewController alloc] initWithFrame:frame target:self action:@selector(stopSearching)];
		[self setOverlayController:newOverlayController];
		[newOverlayController release];
	}
	
	[self.tableView insertSubview:overlayController.view aboveSubview:self.parentViewController.view];

	self.tableView.scrollEnabled = NO;

	searching = YES;
}

- (void) stopSearching {
	self.tableView.scrollEnabled = YES;
	[searchBar resignFirstResponder];
	[overlayController.view removeFromSuperview];
	[overlayController release];
	overlayController = nil;
	searching = NO;
}

//- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar;                        // return NO to not resign first responder
//- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar;                       // called when text ends editing

// called when text changes (including clear)
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
	[self reloadBoozesWithQuery:searchText];
	[[self tableView] reloadData];
}	

// called when keyboard search button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
	[self stopSearching];
}

// called when bookmark button pressed
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar {
	
}

// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
//	UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Alert"message:@"In searchBarCancelButtonClicked" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
//	[myAlert show];
//	[myAlert release];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	// The header for the section is the region name -- get this from the dictionary at the section index
	
	NSInteger sectionCount = [sectionTitles count];
	if (sectionCount < 1) {
		return @"No results found";
	}
	
	return [sectionTitles objectAtIndex:section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
//	return alphabeticSectionTitles;
	return sectionTitles;
}

- (NSInteger)tableView:(UITableView*) tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger) index {

	if (searching) {
		[self stopSearching];
	}
	return index;
}

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/

- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
	self.navigationItem.title = @"Vegan Booze";
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	NSInteger sectionCount = [sectionTitles count];
	
    return sectionCount > 0 ? sectionCount : 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger sectionCount = [sectionTitles count];
	if (sectionCount < 1) {
		return 0;
	}
	
	NSNumber *rowCount = [rowsPerSection objectAtIndex:section];
	return 	[rowCount integerValue];;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	//UILabel *textLabel = [cell textLabel];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
		//textLabel = [cell textLabel];
		[[cell textLabel] setFont:[UIFont systemFontOfSize:14]];
//		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    // Set up the cell...
	NSInteger iStartRowForSection = [[startRowBySection objectAtIndex:[indexPath section]] integerValue];
	[[cell textLabel] setText:[[boozes objectAtIndex:[indexPath row]+iStartRowForSection] objectAtIndex:1]];

	NSString *shortNotes = [[boozes objectAtIndex:[indexPath row]+iStartRowForSection] objectAtIndex:2];
	BOOL notVegan = [[shortNotes lowercaseString] rangeOfString:@"not vegan"].location != NSNotFound; //isEqual:@"Vegan Friendly"];
	BOOL someVegan = ![[shortNotes lowercaseString] isEqual:@"vegan friendly"];

	if (notVegan) {
//		[cell setText:[[boozes objectAtIndex:[indexPath row]+iStartRowForSection] objectAtIndex:2]];
		[[cell textLabel] setTextColor:[UIColor grayColor]];
	}
	else {
		[[cell textLabel] setTextColor:[UIColor blackColor]];	
	}	

	// Set the cell image
	NSString *category = [[[boozes objectAtIndex:[indexPath row]+iStartRowForSection] objectAtIndex:3] lowercaseString];
	
	NSString *iconName = nil;
	if (notVegan) {
		iconName = [NSString stringWithFormat:@"%@_not_vegan_icon_small.png",category];
	}
	else if (someVegan) {
		iconName = [NSString stringWithFormat:@"%@_some_vegan_icon_small.png",category];
	}
	else {
		iconName = [NSString stringWithFormat:@"%@_vegan_icon_small.png",category];
	}

	[[cell imageView] setImage:[UIImage imageNamed:iconName]];

/*	
	if ([category isEqualToString:@"beer"]) {
		cell.image = [UIImage imageNamed:@"beer_vegan_icon.png"];
	}
	else if([category isEqualToString:@"wine"]) {
		cell.image = [UIImage imageNamed:@"wine_icon.png"];
	}
	else if([category isEqualToString:@"liquor"]) {
		cell.image = [UIImage imageNamed:@"liquor_icon.png"];
	}
	else {
		cell.image = nil;
	}
 */
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	// Show the booze details by pushing a BoozeDetailsViewController onto the navigation controller	
	/*
	NSInteger iStartRowForSection = [[startRowBySection objectAtIndex:[indexPath section]] integerValue];
	BoozeDetailsViewController *detailsViewController = [[BoozeDetailsViewController alloc] initWithVendorId:[[[boozes objectAtIndex:[indexPath row]+iStartRowForSection] objectAtIndex:0] integerValue] database:database];
	[self.navigationController pushViewController:(UIViewController *)detailsViewController animated:YES];
	[detailsViewController release];
	 */
	NSInteger iStartRowForSection = [[startRowBySection objectAtIndex:[indexPath section]] integerValue];
	BoozeCompanyVC *companyViewController = [[BoozeCompanyVC alloc]  initWithCompanyId:[[[boozes objectAtIndex:[indexPath row]+iStartRowForSection] objectAtIndex:0] integerValue] database:database];
	[self.navigationController pushViewController:(UIViewController *)companyViewController animated:YES];
	[companyViewController release];	
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
//	[searchBar release];
	[boozes release];
	[sectionTitles release];
	[rowsPerSection release];
	[startRowBySection release];
	[overlayController release];
	
    [super dealloc];
}

@end

